import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, Switch, message, Icon, Dropdown, Menu, Divider, Drawer, Button, Form, Input, Badge, Modal, Table, Select } from 'antd';
import { BaseForm } from '@/components/FormTools';
import { getSelectList, getChannelList, saveEditChannel } from '@/services/auth';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { getValue, to } from '@/utils/smallTool';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import Permission from '@/utils/Authorized';
import styles from './index.less';
import { get } from 'lodash';
import authUtil from '@/utils/auth';
const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 20 };
const drawerWidth = '30%';
const dateFormat = 'YYYY-MM-DD' || undefined;
const curDate = new Date();
const preDate = new Date(curDate.getTime());
const nextDate = new Date(curDate.getTime());
const INTERFACE = 'interface_enable';
@Form.create({})
@connect(({ global, loading, channel, authority }) => ({
  tableData: channel.tableData,
  searchForm: channel.searchForm,
  permissionsList: authority.permissionsList,
  tableLoading: loading.effects['channel/getChannelList'],
  watermarkConfig: global.watermarkConfig,
}))
class ChannelSetting extends PureComponent {
  constructor(props) {
    super(props);
    this.$drawerForm = React.createRef();
    this.state = {
      drawerStatus: {
        visible: false,
        type: 'add',
      },
      resultDate: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
      },

      params: {},
      inputConfig: [
        {
          type: 'select',
          placeholder: '请选择接口名称',
          name: 'businessId',
          optionData: [],
          label: '接口名称', 
          selectProps: {
            allowClear: true,
          }
        }
      ],
      editInputConfig: [
        {
          type: 'input',
          placeholder: '请选择接口名称',
          name: 'businessName',
          label: '接口名称',
        },
        {
          type: 'input',
          placeholder: '渠道名称',
          name: 'channelName',
          label: '渠道名称',
          disabled: true,
          // selectProps: { onChange: value => this.selectHandelChange(value) },
        },
        {
          type: 'select',
          placeholder: '接口状态',
          name: 'status',
          label: '接口状态',
        },
        {
          name: 'businessId'
        },
        {
          name: 'channelId'
        } 
      ],
      configData: {}
    };
    this.searchForm = React.createRef();
    this.getSelectList().then(data => {
      this.setState({configData: data});
      this.getQueryList(this.state.params, this.state.pageRequest);
    });
  }

  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };
  saveEditHandler = async (formData) => {
    const { editInputConfig } = this.state;
    const params = Object.fromEntries(editInputConfig.map(function(item) {
      let _value = item.value || item.defaultValue;
      return [`${item.name}`, _value]
    }))
    const dataObj = await saveEditChannel(params);
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data == null) {
        this.getQueryList(this.state.params, this.state.pageRequest);
        this.changeDrawerStatus(false);
      }
    }
  };
  //获取二级分类
  selectHandelChange = event => {
    console.log(event);
    // this.getTwoLevelList(event);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'channel/getChannelList';
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: {pageRequest: pageRequest, ...params},
    });
  };

  /**
   * @description 请求一级模块下拉列表
   * @author zlh
   * @date 2021-05-08
   * @memberof
   */
  getSelectList = async () => {
    const { inputConfig, editInputConfig } = this.state;
    const key = 'interface_id';
    const dataObj = await getSelectList({constKeys: [key, INTERFACE]});
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data != null) {
        const arrObj = [];
        Object.entries(dataObj.data[key]).map(item => {
          arrObj.push({ name: item[1], value: item[0] });
        });
        inputConfig[0].optionData = arrObj;
        this.setState({ 
          inputConfig: inputConfig
        });
        return Promise.resolve(dataObj.data);
      }
    }
    return Promise.reject();
  };
  /**
   * @description table操作触发改变事件
   * @author songs
   * @date 2019-07-12
   * @param {*} pagination
   * @param {*} filtersArg
   * @param {*} sorter
   * @memberof managementUser
   */
  handleStandardTableChange = (pagination, filtersArg, sorter, actionType) => {
    const { pageSize, current } = pagination;
    const pageRequest = { pageSize, pageNum: current };
    this.getQueryList(filtersArg, pageRequest);
  };
  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} type
   * @param {*} title
   */
  changeDrawerStatus = (visible, type = '', index = {}, event) => {
    if (visible) {
      const { editInputConfig, configData } = this.state;
      const channelItem = this.props.tableData.list[index];
      editInputConfig[0].defaultValue = channelItem.businessName;
      editInputConfig[1].defaultValue = channelItem.channelName;
      editInputConfig[2].defaultValue = configData[INTERFACE][channelItem.status];
      editInputConfig[3].defaultValue = channelItem.businessId;
      editInputConfig[4].defaultValue = channelItem.channelId;
      this.setState({
        editInputConfig: editInputConfig
      });
    }
    this.setState({
      drawerStatus: { type, visible },
    });
  };
  tableCol = () => {
    const { tableData } = this.props;
    const { configData } = this.state;
    const { pagination = {} } = tableData;
    const { pageSize = 50, current = 0 } = pagination;
    const OptionNode = ({ id, index }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          onClick={() => {
            this.changeDrawerStatus(true, 'see', index);
          }}
        >
          编辑
        </Button>
      </div>
    );
    return [
      {
        title: '序号',
        dataIndex: 'id',
      },
      {
        title: '接口名称',
        dataIndex: 'businessName',
      },
      {
        title: '在用渠道名称',
        dataIndex: 'channelName',
        render: (text, record) => { return record.channelId + '-' + text }
      },
      {
        title: '设置时间',
        dataIndex: 'createTime',
        render: text => { return authUtil.formatDate(text, 'Y-M-D h:m:s')}
      },
      {
        title: '接口状态',
        dataIndex: 'status',
        render: text => { 
          return configData[INTERFACE] && configData[INTERFACE][text]
        }
      },
      {
        title: '最后一次操作人',
        dataIndex: 'operator',
      },
      {
        title: '接口能力说明',
        dataIndex: 'businessDesc',
      },
      {
        title: '编辑',
        width: 120,
        render: (text, record, index) => (<OptionNode id={text} index={index} record={record}></OptionNode>),
      },
    ];
  };
  onStatusChange(e) {
    const { editInputConfig, configData } = this.state;
    editInputConfig[2].defaultValue = configData[INTERFACE][e];
    editInputConfig[2].value = e;
    this.setState({
      editInputConfig: editInputConfig
    })
  };
  render() {
    const { tableCol, changeDrawerStatus, onStatusChange, saveEditHandler } = this;
    const { inputConfig, drawerStatus, resultDate, editInputConfig } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    const content = (
      <div>
        <Permission authority="notice:button-inBoxMsgPush">
          <span style={{ float: 'left', fontSize: '16px', fontWeight: 'bold' }}>渠道设置列表</span>
        </Permission>
      </div>
    );
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              wrappedComponentRef={this.searchForm}
              defaultInput={inputConfig}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <div style={{ marginBottom: '10px', height: '32px', lineHeight: '32px' }}>{content}</div>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              //rowKey='id'
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'channel/getChannelList');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title={'渠道编辑'}
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false);
          }}
          visible={drawerStatus.visible}
          footer={[
            <div className={styles.footer}>
              <Button
                onClick={e => {
                  changeDrawerStatus(false);
                }}
                style={{ marginRight: 8 }}
              >
                取消
              </Button>
            </div>
          ]}
        >
            <Form onSubmit={saveEditHandler}>
              <Form.Item label="接口名称" name="businessName">
                <Input disabled={true} defaultValue={editInputConfig[0].defaultValue} id="businessName"/> 
              </Form.Item>
              <Form.Item label="渠道名称" name="channelId">
                <Input disabled={true} defaultValue={editInputConfig[1].defaultValue} id="channelId"/>
              </Form.Item>
              <Form.Item label="渠道状态" name="status">
              <Select onChange={onStatusChange.bind(this)} defaultValue={editInputConfig[2].defaultValue}>
                  <Option value="0">启用</Option>
                  <Option value="1">禁用</Option>
              </Select>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">确定</Button>
              </Form.Item>
            </Form>
        </Modal>
      </div>
    );
  }
}

export default ChannelSetting;
